package com.yswy.backstage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.obs.services.model.PutObjectResult;
import com.yswy.backstage.service.AppProjectService;
import com.yswy.backstage.service.PackageManageLogService;
import com.yswy.backstage.service.PackageManageService;
import com.yswy.backstage.service.PackageVersionService;
import com.yswy.common.enums.TfPlatformEnums;
import com.yswy.common.enums.XtPlatformEnums;
import com.yswy.common.enums.base.TypeEnum;
import com.yswy.common.utils.CommandUtil;
import com.yswy.common.utils.HuaWeiYunOBSUtil;
import com.yswy.common.utils.ImageBioChangeUtil;
import com.yswy.common.utils.StringUtils;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.domain.common.BasePojo;
import com.yswy.domain.entity.AppProject;
import com.yswy.domain.entity.PackageManage;
import com.yswy.domain.entity.PackageManageLog;
import com.yswy.domain.entity.PackageVersion;
import com.yswy.domain.entity.user.User;
import com.yswy.domain.framework.context.CurrentUserContext;
import com.yswy.domain.mapper.PackageManageLogMapper;
import com.yswy.domain.mapper.PackageManageMapper;
import com.yswy.domain.vo.gld.addOrUpate.PackageManageAddOrUpdate;
import com.yswy.domain.vo.gld.list.PackageManageLogList;
import com.yswy.domain.vo.gld.search.PackageManageIdSearch;
import com.yswy.domain.vo.gld.search.PackageManageSearch;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.zip.CRC32;

import static com.yswy.backstage.utils.CrudUtils.selectCount;
import static com.yswy.common.constants.WarnMsgConstants.NULL_MSG;


@Slf4j
@Service
public class PackageManageLogServiceImpl extends ServiceImpl<PackageManageLogMapper, PackageManageLog>
        implements PackageManageLogService {
    @Autowired
    private HuaWeiYunOBSUtil huaWeiYunOBSUtil;
    @Autowired
    private PackageVersionService packageVersionService;
    @Autowired
    private PackageManageService packageManageService;
    @Autowired
    private AppProjectService appProjectService;

    @Value(value = "${package.path}")
    private String path ;
    @Value(value = "${package.outPath}")
    private String outPath ;
    @Value(value = "${package.outPathDownload}")
    private String outPathDownload ;
//    private final static String path = "/opt/walle/";
//    private final static String outPath = "/opt/walle/";
//    private final static String outPathDownload = "/opt/walle/download/";

    @Override
    public Page<PackageManageLogList> pagePackageManageLog(PackageManageIdSearch res) {
        PackageManage packageManage = packageManageService.getById(res.getPackageManageId());
        //判断是否有新版本 更新新版本
        List<PackageVersion> packageVersions = baseMapper.getNewPackageVersionByManageLog(packageManage.getProjectId());
        if (packageVersions.size()>0){
            List<PackageManageLog> packageManageLogs = new ArrayList<>();
            for (PackageVersion pv:packageVersions) {
                PackageManageLog packageManageLog = new PackageManageLog();
                packageManageLog.setPackageManageId(packageManage.getId());
                packageManageLog.setPackageVersionId(pv.getId());
                packageManageLog.setVersion(pv.getVersion());
                packageManageLog.setVersionCode(pv.getVersionCode());
                packageManageLog.setIsRenew(0);
                packageManageLog.setXtPlatform(packageManage.getXtPlatform());
                packageManageLog.setCreateBy(1l);
                packageManageLogs.add(packageManageLog);
            }
            saveBatch(packageManageLogs);
        }
        Page<PackageManageLogList> packageManageLogLists = baseMapper.pagePackageManageLog(res.getPackageManageId()
                , new Page<>(res.getPageNum() , res.getPageSize()) );
        for (PackageManageLogList packageManageLogList:packageManageLogLists.getRecords()){
            TypeEnum xtPlatformEnum = TypeEnum.typeEnumOf(XtPlatformEnums.class , packageManageLogList.getXtPlatform());
            packageManageLogList.setXtPlatform(xtPlatformEnum.getMessage());
        }
        return packageManageLogLists;
    }

    @Override
    public void updateIsRenew(Long packageManageLogId, Integer isRenew) {
        User user = CurrentUserContext.getCurrentUser();
        Integer count = selectCount(baseMapper, s -> s.eq(BasePojo::getId, packageManageLogId));
        Assert.state(null != count && 0 < count, "未找到指定信息，请刷新重试");
        PackageManageLog bo = getById(packageManageLogId);
        BasePojo.setBase(user.getId().longValue(), false, bo);
        bo.setIsRenew(isRenew);

        updateById(bo);
    }

    @Override
    public void newPackageManageLog(PackageManage packageManage ) {
        User user = CurrentUserContext.getCurrentUser();
        PackageVersion packageVersion = packageVersionService.getMaxVersion(packageManage.getProjectId());
        if (packageVersion == null){
            return;
        }
        AppProject appProject = appProjectService.getById(packageManage.getProjectId());
        packaging( null, packageVersion , packageManage  ,  appProject , user );

    }

    @Override
    public void addPackageManageLog( Long packageManageLogId ) {
        User user = CurrentUserContext.getCurrentUser();
        PackageManageLog packageManageLog = getById(packageManageLogId);
        Assert.state(null != packageManageLog , "未找到指定信息，请刷新重试");


        PackageVersion packageVersion = packageVersionService.getById(packageManageLog.getPackageVersionId());
        PackageManage packageManage = packageManageService.getById(packageManageLog.getPackageManageId());
        AppProject appProject = appProjectService.getById(packageManage.getProjectId());
        packaging(packageManageLog,  packageVersion , packageManage  ,  appProject , user );

    }
    private void packaging(PackageManageLog packageManageLog ,
                           PackageVersion packageVersion ,PackageManage packageManage  , AppProject appProject ,User user ){
        if (packageVersion == null || packageManage == null  || appProject == null){
            throw new IllegalStateException("参数缺失");
        }
        Long uid = getUid ();
        String apkUrl =  AutomaticPackaging(packageVersion.getFileUrl() , uid ,
                appProject.getId() ,
                appProject.getProjectName(),
                packageVersion.getVersionCode()
                , packageManage.getChannel());
        if (StringUtils.isEmpty(apkUrl)){
            throw new IllegalStateException("打包失败");
        }
        if (packageManageLog == null){
            packageManageLog = new PackageManageLog();
            packageManageLog.setPackageManageId(packageManage.getId());
            packageManageLog.setPackageVersionId(packageVersion.getId());
            packageManageLog.setUid(uid);
            packageManageLog.setFileUrl(apkUrl);
            packageManageLog.setVersion(packageVersion.getVersion());
            packageManageLog.setVersionCode(packageVersion.getVersionCode());
            packageManageLog.setIsRenew(0);
            packageManageLog.setXtPlatform(packageManage.getXtPlatform());
            packageManageLog.setCreateBy(user.getId().longValue());
            save(packageManageLog);
        }else {
            packageManageLog.setFileUrl(apkUrl);
            updateById(packageManageLog);
        }

    }

    private String AutomaticPackaging(String aplUrl ,Long uid ,
                                      Long projectId ,
                                      String  projectName,
                                      String  versionCode
                                        , String channel){

        //下载源文件
        InputStream  oldapkinputStream = ImageBioChangeUtil.returnBitMap(aplUrl);
        String oldapkPath = outPathDownload+uid+".apk";
        File outFile = new File(oldapkPath);
        ImageBioChangeUtil.copyInputStreamToFile(oldapkinputStream,outFile);

        //生成新的apk
        String outFilename = projectName+"_"+channel+"_"+versionCode+"_"+uid+".apk" ;
        String outFilePath = outPath+outFilename;
        String cmd = "java -jar "+path+"walle-cli-all.jar " +
                "put -c " +channel +
                " -e uid="+uid +",projectId="+projectId+
                " " +oldapkPath+
                " " +outFilePath;

        System.out.println(cmd);
        CommandUtil.execCMD(cmd , null , 1000);
        File newFile = new File(outFilePath);
        if (newFile.exists()){
            //上传华为云
            InputStream inputStream = null;
            try {
                inputStream = new FileInputStream(newFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            PutObjectResult newResult = huaWeiYunOBSUtil.upload(outFilename , "datePlatform/PackageDynamic",inputStream);
            String newApkUrl = newResult.getObjectUrl();
            newApkUrl = newApkUrl.replace("%2F" , "/");
            System.out.println(newApkUrl);
            //删除文件
            newFile.delete();
            return newApkUrl ;
        }
        return null;
    }
    private static Long getUid(){
        String uuid = UUID.randomUUID().toString();
        CRC32 crc32 = new CRC32();
        crc32.update(uuid.getBytes());
        return crc32.getValue();
    }


    public static void main(String[] args) {

//        InputStream  oldapkinputStream = ImageBioChangeUtil.returnBitMap(
//                "https://imgeffect.obs.cn-north-1.myhuaweicloud.com:443/datePlatform%2FPackageVersion%2F3af7b391-16b3-4794-907b-308b7159498c.apk");
//        String oldapkPath = outPathDownload+ getUid()+".apk";
//        File outFile = new File(oldapkPath);
//        ImageBioChangeUtil.copyInputStreamToFile(oldapkinputStream,outFile);
    }
}
